﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_DSJCJ.Common;
using System.Data;
using Webdiyer.WebControls.Mvc;
using System.Text;
using Newtonsoft.Json;
using System.Drawing;

namespace ElingOA6_DSJCJ.Controllers
{
    /// <summary>
    /// 问卷调查
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class PaperController : Controller
    {
        //
        // GET: /Paper/
        //public PaperController()
        //{

        //}
        private BLL.Common commonBLL = new BLL.Common();
        private BLL.Paper paperBLL = new BLL.Paper();
        private BLL.PaperTopic paperTopicBLL = new BLL.PaperTopic();
        private BLL.PaperAnswerOption paperAnswerOptionBLL = new BLL.PaperAnswerOption();
        private BLL.PaperAnswer paperAnswerBLL = new BLL.PaperAnswer();
        private BLL.PaperAnswerManager paperAnswerManagerBLL = new BLL.PaperAnswerManager();
        private BLL.PaperIP paperIPBLL = new BLL.PaperIP();


        public List<Model.Paper> GetPageList(int pageSize, out int total, int pageIndex = 1)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            string fieldOrder = " FPaperId";
            string strWhere = " FEntityNo='" + entityNo + "' AND FPaperType='D'";
            string fiedls = "*";
            string tableName = "t_Paper";
            DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 0, out total);
            List<Model.Paper> pagerList = ViewDataRowToModel.DataTableToListPaper(ds.Tables[0]);


            return pagerList;
        }

        public ActionResult Index(int id = 1)
        {
            //return View();
            int pageSize = 1;
            int total = 0;

            List<Model.Paper> tmpPagerList = GetPageList(pageSize, out total, id);
            PagedList<Model.Paper> pagerList = new PagedList<Model.Paper>(tmpPagerList, id, pageSize, total);
            return View(pagerList);
        }
        /// <summary>
        /// 调查答题
        /// </summary>
        /// <param name="paperId"></param>
        /// <returns></returns>
        public ActionResult PaperTopic(int paperId)
        {
            ActionResult actionResult = null;
            Model.Paper paperModel = paperBLL.GetModel(paperId);
            if (paperModel != null)
            {
                DateTime serverTime = commonBLL.GetServerDateTime();
                if (!paperModel.FBeginDate.HasValue)
                {
                    paperModel.FBeginDate = serverTime;
                }
                if (!paperModel.FEndDate.HasValue)
                {
                    paperModel.FEndDate = serverTime;
                }
                else
                {
                    paperModel.FEndDate = DateTime.Parse(paperModel.FEndDate.Value.ToString("yyyy-MM-dd") + " 23:59:59");
                }
                TimeSpan ts = paperModel.FBeginDate.Value - serverTime;
                if (ts.TotalDays > 0)
                {
                    Response.Write("<script>alert('调查还未开始,开始时间为:" + paperModel.FBeginDate.Value.ToString("yyyy-MM-dd") + "');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }
                else
                {
                    //判断是否已经结束
                    ts = paperModel.FEndDate.Value - serverTime;
                    if (ts.TotalDays < 0)
                    {
                        //调查时间已经结束
                        return PaperAnswer(paperId);
                    }
                    else
                    {
                        //判断是否已经答题
                        string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                        string ipAddress = GenerateUtil.GetClientIPv4Address();
                        if (paperModel.FIsRecordName == "Y")
                        {
                            if (!string.IsNullOrEmpty(emplNo))
                            {
                                if (paperAnswerManagerBLL.ExistsByIpAndEmplNo(ipAddress, emplNo,
                                    paperId, GlobalConstant.ENTITYNO))
                                {
                                    //已经答过了
                                    return PaperAnswer(paperId);
                                }
                            }
                            else
                            {
                                //Response.Write("<script>alert('请先登录');window.close();</script>");
                                Response.Write("<script>alert('请先登录');window.location.href='/ElingOA6_Admin/Login?url=/Paper/PaperTopic?paperId=" + paperId + "';</script>");
                                Response.Flush();
                                Response.End();
                                return null;
                            }
                        }
                        else
                        {
                            if (paperAnswerManagerBLL.ExistsByIp(ipAddress, paperId, GlobalConstant.ENTITYNO))
                            {
                                //已经答过了
                                return PaperAnswer(paperId);
                            }
                        }
                        List<Model.PaperIP> pagerIPList = paperIPBLL.GetListPaperIP(paperId);
                        //判断是否控制问卷参与IP
                        if (paperModel.FIsVoteIPControl == "Y")
                        {

                            List<Model.PaperIP> pagerIPControlList = pagerIPList.Where(s => s.FProp == "1").ToList();
                            string ipList = "";
                            foreach (Model.PaperIP paperIPModel in pagerIPControlList)
                            {
                                ipList += paperIPModel.FIPGroupID + ",";
                            }
                            if (ipList != "")
                            {
                                ipList = ipList.Substring(0, ipList.LastIndexOf(','));
                            }
                            if (!Fetch.IpCheck("1", ipList))
                            {
                                Response.Write("<script>alert('IP受限制,无法参与问卷');window.close();</script>");
                                Response.Flush();
                                Response.End();
                                return null;
                            }
                        }

                        List<Model.PaperTopic> paperTopicList = paperTopicBLL.GetModelList(paperId);
                        int topicSeqId = 1;
                        ViewData["paperTopicList"] = paperTopicList;
                        ViewData["topicSeqId"] = topicSeqId;
                        actionResult = View("PaperTopicDC", paperModel);
                    }
                }
            }
            else
            {
                actionResult = View("Error");
            }
            return actionResult;
        }
        /// <summary>
        /// 查看结果
        /// </summary>
        /// <param name="paperId"></param>
        /// <param name="chartType">1-饼图 2-柱状图</param>
        /// <returns></returns>
        public ActionResult PaperAnswer(decimal paperId, int chartType = 1)
        {
            ActionResult actionResult = null;
            Model.Paper paperModel = paperBLL.GetModel(paperId);
            if (paperModel != null)
            {
                string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                string entityNo = GlobalConstant.ENTITYNO;
                bool isLook = true;//是否可查看
                //这里判断查看权限
                //是否控制查看权限
                if (paperModel.FResultIsOpen == "N")
                {
                    if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                    {
                        isLook = false;
                    }
                    else
                    {
                        if (!paperBLL.IsPaperAuthorityForEmpl(empNo,deptNo, paperId, entityNo))
                        {
                            isLook = false;
                        }
                    }
                }

                if (isLook)
                {

                    List<Model.PaperTopic> paperTopicList = paperTopicBLL.GetModelList(paperId);
                    int topicSeqId = 1;
                    ViewData["paperTopicList"] = paperTopicList;
                    ViewData["topicSeqId"] = topicSeqId;



                    //统计答案
                    string chartData = "[";
                    foreach (Model.PaperTopic paperTopicModel in paperTopicList)
                    {
                        if (chartType == 1)
                        {
                            //饼图数据
                            DataSet ds = paperAnswerBLL.GetListGroupByAnswer(paperTopicModel.FPaperTopicId);
                            DataTable dt = ds.Tables[0];
                            int rowsCount = dt.Rows.Count;
                            if (rowsCount > 0)
                            {
                                chartData += "[";
                                for (int n = 0; n < rowsCount; n++)
                                {
                                    if (dt.Rows[n]["FAnswer"] != null)
                                    {
                                        chartData += "{\"country\":\"" + dt.Rows[n]["FAnswer"].ToString() + "\",";
                                        chartData += "\"value\":" + dt.Rows[n]["census"].ToString() + ",";
                                        chartData += "\"aw\":\"" + dt.Rows[n]["aw"].ToString() + "\",";
                                        chartData += "\"id\":" + (paperTopicModel.FPaperTopicId) + "},";

                                    }

                                }
                                //FWriteAnswer += item.FPaperTopicId + ",";
                                chartData = chartData.Substring(0, chartData.LastIndexOf(","));
                                chartData += "],";
                            }
                        }
                        else
                        {
                            //柱状图数据
                            DataSet ds = paperAnswerBLL.GetListGroupByAnswer(paperTopicModel.FPaperTopicId);
                            DataTable dt = ds.Tables[0];
                            int rowsCount = dt.Rows.Count;
                            if (rowsCount > 0)
                            {
                                chartData += "[";
                                Random rand = new Random();
                                for (int n = 0; n < rowsCount; n++)
                                {
                                    Color color = Color.FromArgb(rand.Next());
                                    string strColor = "#" + Convert.ToString(color.ToArgb(), 16).PadLeft(8, '0').Substring(2, 6);
                                    if (dt.Rows[n]["FAnswer"] != null)
                                    {
                                        chartData += "{\"country\":\"" + dt.Rows[n]["FAnswer"].ToString() + "\",";
                                        chartData += "\"visits\":" + dt.Rows[n]["census"].ToString() + ",";
                                        chartData += "\"color\":\"" + strColor + "\",";
                                        chartData += "\"aw\":\"" + dt.Rows[n]["aw"].ToString() + "\",";
                                        chartData += "\"id\":" + (paperTopicModel.FPaperTopicId) + "},";
                                    }

                                }
                                //FWriteAnswer += item.FPaperTopicId + ",";
                                chartData = chartData.Substring(0, chartData.LastIndexOf(","));
                                chartData += "],";
                            }
                        }
                    }
                    if (chartData != "[")
                    {
                        chartData = chartData.Substring(0, chartData.LastIndexOf(",")) + "]";
                    }
                    else
                    {
                        chartData += "]";
                    }
                    ViewData["chartData"] = chartData;
                    ViewData["chartType"] = chartType;
                    actionResult = View("PaperAnswerDC", paperModel);
                }
                else
                {
                    Response.Write("<script>alert('你未登录或者无权限查看问卷结果');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }
            }
            else
            {
                actionResult = View("Error");
            }
            return actionResult;
        }
        public ActionResult PaperAnswerList(decimal autoID, int paperType)
        {
            List<Model.PaperAnswer> paperAnswerList = new List<Model.PaperAnswer>();
            BLL.PaperAnswer paperAnswerBLL = new BLL.PaperAnswer();
            paperAnswerList = paperAnswerBLL.GetModelList("FPaperTopicId=" + autoID + "and FWriteAnswer<>''");
            if (paperType == 0)
            {
                BLL.PaperTopic paperTopicBLL = new BLL.PaperTopic();
                Model.PaperTopic paperTopicModel = new Model.PaperTopic();
                List<Model.PaperTopic> paperTopicList = new List<Model.PaperTopic>();
                paperTopicModel = paperTopicBLL.GetModel(autoID);
                ViewData["FStdAnswer"] = "";
                if (paperTopicModel != null)
                {
                    ViewData["FStdAnswer"] = paperTopicModel.FStdAnswer;
                }
            }
            return View(paperAnswerList);
        }
        public ActionResult Save()
        {
            ActionResult actionResult = null;

            Model.PaperAnswerManager paperAnswerManagerModel = new Model.PaperAnswerManager();

            Model.PaperAnswer paperAnswerModel = new Model.PaperAnswer();
            List<Model.PaperAnswer> paperAnswerList = new List<Model.PaperAnswer>();
            if (Fetch.Post("hidpaper") != "")
            {

                paperAnswerList = JsonConvert.DeserializeObject<List<Model.PaperAnswer>>(Fetch.Post("hidpaper"));

                decimal paperId = decimal.Parse(Fetch.Post("hidFPaperId"));
                Model.Paper paperModel = paperBLL.GetModel(paperId);
                if (paperModel != null)
                {
                    paperAnswerManagerModel.FSurverName = Fetch.Post("SurveyTargetName") == "" ? "匿名" : Fetch.Post("SurveyTargetName");
                    paperAnswerManagerModel.FSurverContact = Fetch.Post("SurveyTargetContact");
                    paperAnswerManagerModel.FSurverUnitName = Fetch.Post("SurverUnitName");
                    paperAnswerManagerModel.FSurverAddress = Fetch.Post("SurverAddress");
                    paperAnswerManagerModel.FSurverPostCode = Fetch.Post("SurverPostCode");
                    paperAnswerManagerModel.FSurverEMail = Fetch.Post("SurverEMail");
                    if (paperModel.FIsRecordName == "Y")
                    {

                        paperAnswerManagerModel.FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                        paperAnswerManagerModel.FIp = Common.GenerateUtil.GetClientIPv4Address();

                        if (!string.IsNullOrEmpty(paperAnswerManagerModel.FEmplNo))
                        {
                            if (!paperAnswerManagerBLL.ExistsByIpAndEmplNo(paperAnswerManagerModel.FIp, paperAnswerManagerModel.FEmplNo,
                                paperId, GlobalConstant.ENTITYNO))
                            {
                                paperAnswerManagerModel.FEntityNo = GlobalConstant.ENTITYNO;
                                paperAnswerManagerModel.FDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                                paperAnswerManagerModel.FAnswerDate = DateTime.Now.ToString();

                                paperAnswerManagerModel.FPaperId = paperId;
                            }
                            else
                            {
                                ViewData["errorMessage"] = "一位员工一个ip只能提交一次";
                                actionResult = View("Error");
                            }

                        }
                        else
                        {
                            ViewData["errorMessage"] = "请先登录";
                            actionResult = View("Error");
                        }
                    }
                    else
                    {
                        if (!paperAnswerManagerBLL.ExistsByIp(paperAnswerManagerModel.FIp, paperId, GlobalConstant.ENTITYNO))
                        {

                        }
                        else
                        {
                            ViewData["errorMessage"] = "一个ip只能提交一次";
                            actionResult = View("Error");
                        }
                    }
                    if (actionResult == null)
                    {



                        try
                        {

                            paperAnswerBLL.AddItem(paperAnswerManagerModel, paperAnswerList);

                            Response.Write("<script>window.alert('保存成功！');window.location.href = '/Paper/PaperAnswer?paperId=" + paperId + "';</script>");
                            Response.Flush();
                            Response.End();
                        }
                        catch (Exception ee)
                        {
                            ViewData["errorMessage"] = "操作异常" + ee.Message;
                            actionResult = View("Error");
                        }

                    }

                }

                else
                {
                    actionResult = View("Error");
                }

            }

            return actionResult;
        }

    }
}
